package cn.ly.rabbit.rabbitListener;

import cn.ly.rabbit.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 简单队列。即Rabbitmq默认的Direct交换器，且routeKey即该Queue_name
 */
@Component
@RabbitListener(queues = RabbitConfig.Simple_Queue_Name)  //这里监听叫hello.queue的队列
public class SimpleQueueListener {

    @RabbitHandler
    public void process(String map, Channel channel, Message message)  {
        try {
            //拿到消息
            String mm = new String(message.getBody());
            System.out.println(">>>>>>>>>>>>>>msg:"+mm);
            //...业务l逻辑
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  //第二个参数表示批量确认
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);   //第二个参数表示是否重新返回队列：requeue
            } catch (IOException e1) {
                System.out.println(">>>>>>>>>>>>>>>拒绝报错");
            }
        }
    }
}
